const api = require("../../util/api");

// pages/ucenter/user/info.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: [],
    isEdit: true,
    index: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    let userId = options.userId;
    
    api.listRoles().then(res=>{
      _this.setData({
        array: res,
        index: api.getDicIndex(options.roleKey, res, 'value'),
        item:{
          roleName : res[_this.data.index].label
        }
      });
    });

    if(api.isBlank(userId)){
      _this.setData({
        isEdit: false
      });
      return;
    }
    
    api.get(`${api.url.user}/${userId}`).then(res=>{
      _this.setData({
        item: res.data
      });
    });
    api.get(`${api.url.wechatUserList}`,{
      userId: userId,
      appid: api.appid
    }).then(res=>{
      _this.setData({
        wechatUser: res.rows[0]
      });
    });
  },
  bindPickerChange: function (e) {
    let _this = this;
    let item = _this.data.item;
    item.roleName = _this.data.array[e.detail.value].label;
    _this.setData({
      index: e.detail.value,
      item: item
    });
  },
  bindInputChange(e){
    let name = e.currentTarget.dataset.name;
    let value = e.detail.value;
    let item = this.data.item;
    item[name] = value;
    this.setData({
      item: item
    });
  },
  updateUser(e) {
    let _this = this;
    var params = e.detail.value;
    if (api.isBlank(params.roleName)) {
      wx.showToast({
        title: "角色不能为空",
        icon: "none"
      });
      return;
    }
    if (api.isBlank(params.userName)) {
      wx.showToast({
        title: "姓名不能为空",
        icon: "none"
      });
      return;
    }
    if (api.isBlank(params.phonenumber)) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none"
      });
      return;
    }
    if(_this.data.isEdit){
      api.put(api.url.user, params).then(res => {
        api.back("修改成功", "success");
      })
    }else{
      api.post(api.url.user, params).then(res => {
        api.back("新增成功", "success");
      })
    }
  }
})